package com.yb.framework.security.handler;

import java.io.IOException;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import com.yb.framework.core.constant.Constants;
import com.yb.framework.core.utils.DateUtil;
import com.yb.framework.core.utils.ExceptionUtil;
import com.yb.framework.core.utils.IpUtil;
import com.yb.framework.core.utils.SnowflakeIdWorker;
import com.yb.module.system.domain.SysLogLogin;
import com.yb.module.system.service.SysLogLoginService;

@Component
public class AuthenticationFailureHandlerImpl extends SimpleUrlAuthenticationFailureHandler {
	
	@Autowired
	private SysLogLoginService sysLogLoginService;
	
	private final Logger logger = LoggerFactory.getLogger(AuthenticationFailureHandlerImpl.class);	
	@Override
	public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
			AuthenticationException exception) throws IOException, ServletException {
		// TODO Auto-generated method stub
		// 修改异常信息
		if("Bad credentials".equals(exception.getMessage())) {
			exception = new BadCredentialsException("用户名密码错误，请重试");
		}
		// 打印异常日志
		logger.error("用户[" + request.getParameter("username") + "]，登录系统失败", exception);
		
		// 记录登录日志
		Date loginTime = new Date();
		SysLogLogin sysLogLogin = new SysLogLogin();
		sysLogLogin.setId(SnowflakeIdWorker.getInstance().getId());
		sysLogLogin.setLoginUser(request.getParameter("username"));
		sysLogLogin.setMessage(request.getParameter("username") + " ，" + DateUtil.date2String(loginTime, null) + " 登录系统失败");
		sysLogLogin.setExceptionMsg(ExceptionUtil.getStackTrace(exception));
		sysLogLogin.setIpAddr(IpUtil.getIpAddr(request));
		sysLogLogin.setStatus(Constants.ERROR);
		sysLogLogin.setLoginTime(new Date());
		sysLogLoginService.insertLogAsync(sysLogLogin);
		
		// 将异常信息存到session中（供前端获取）
		saveException(request, exception);
		// 跳转登录界面（前端通过error参数，生成告警信息）
		response.sendRedirect("/login?error");
	}
}
